<template>
  <div :id = "tableId" style = "position: relative;" @contextmenu.prevent.stop>
    <right-key-menu :ref = "tableId+'menu'" :menu-list = "menuList"/>
    <!-- <set-type-tip :ref="tableId+'setTypeTip'" :table-id="tableId" :table-model="tableModel" /> -->
    <group-box-container class = "dynamic-table-wapper" :form-datas = "formDatas" :form-item = "field.preps"
    >
      <table
          v-if = "reflush"
          :key = "field.preps.rowAndCols.length"
          class = "dynamic-table"
          border = "1"
          :class = "{'isPreview':!isEdit,'noPreview':isEdit}"
          @mousedown = "mouseDown"
          @mousemove = "mouseMove"
          @mouseup = "mouseUp"
          @mouseleave = "endSelect"
          @contextmenu = "getMenu"
      >
        <!--                <colgroup v-for="item in cols" :key="item" :style="{width: 1/cols*100 +'%'}"/>-->
        <tr v-for = "(tr,row) in field.preps.rowAndCols" :key = "'throw'+row">
          <template v-for = "(td,col) in tr.colAndDatas">
            <td

                :rowspan = "td.rowspan || 1"
                :colspan = "td.colspan || 1"
                :align = "alignDict[tr.align]"
                :valign = "valignDict[tr.valign]"
                style = "color: #8691A0;"
                :style = "{ 'height':'35px',
                                        width:(100/tr.cols)+'%',
                                        borderTop: `1px solid  #dfe6ec`,
                                        borderBottom: `1px solid #dfe6ec`,
                                        borderLeft: `1px solid #dfe6ec`,
                                        borderRight: `1px solid #dfe6ec`,
                                        backgroundColor: td.cellFill
                                        }"
                :dataSelectFlag = "`td-${row}-${col}-${td.rowspan}-${td.colspan}`"
                :class = "{'cell':true,'brder-bottom-none':true}"
            >
              <draggable @add = "(evt)=>onDragAdd(evt,td.datas)" class = "smain-design"
                         tag = "div"
                         v-bind = "{group:'starHorseGroup', ghostClass: 'ghost',animation: 200}"
                         v-model = "td.datas">
                <template v-for = "data in td.datas">
                  <!--                                    <component :field="data" :form-datas="formDatas" :is="data.type+'-container'"
                                                                 @selectItem="selectItem" v-if="data.compType==='container'">
                                                      </component>-->
                  <component :field = "data" :form-datas = "formDatas" :is = "getComponentName(data)"
                             @selectItem = "selectItem" v-if = "data.compType==='formItem'"/>
                  <component :is = "unknown-item" v-else/>
                </template>

              </draggable>
            </td>
          </template>
        </tr>
      </table>
      <div
          v-if = "isShowNoData"
          class = "d-flex j-center"
          :style = "{
          borderTop: `1px solid ${options.rowBorderColor ? options.rowBorderColor : '#dfe6ec'}`}"
      >
        <v-noData/>
      </div>
    </group-box-container>
  </div>
</template>

<script>
// 右键菜单组件
import RightKeyMenu from './right-key-menu.vue'
import EvolInput from './evol-input.vue'
import GroupBoxContainer from "./group-box-container";
import UserComponents2 from "../allitem";
import {inject} from "vue";

/**
 * 动态表格
 */
export default {
  name: "table-container",
  components: {
    RightKeyMenu,
    EvolInput, GroupBoxContainer, ...UserComponents2
  },
  props: {
    field: {type: Object},
    formDatas: {type: Object}


  },
  setup() {
    let editable = inject("tableEditable");
    return {
      editable
    }
  },
  data() {
    return {
      dataComplete: false, // 数据加载完成标志
      sizeDict: {
        '小': '11px',
        '中': '13px',
        '大': '15px'
      },
      alignDict: {
        '左': 'left',
        '中': 'center',
        '右': 'right'
      },
      valignDict: {
        '上': 'top',
        '中': 'middle',
        '下': 'bottom'
      },
      reflush: true, // 强制刷新表格
      // 对齐方式
      result: 0,
      cellHeight: 30, // 一个单元格的基础高度
      cellWidth: 25,
      tableId: 'evol-' + +new Date(),
      selectCells: [], // 被选中的单元格 标志数组
      cells: null,
      mouseEventDom: null, // 鼠标当前所在单元格
      mouseDownCell: null, // 鼠标按下时的节点
      rightDownCell: null, // 鼠标右键按下的节点
      menuList: [], // 右键菜单列表
      allowMerging: false, // 是否允许合并单元格
      currDataType: 'static',
      defaultVal: [],
      isShowNoData: false,
      isMouseDown: false
    }
  },
  computed: {},
  watch: {
    isMouseDown: {
      handler(val) {
        this.editable = val;
      },
      immediate: true,
      deep: true
    },
    field: {
      handler(val) {
      },
      immediate: true, // 刷新加载 立马触发一次handler
      deep: true // 可以深度检测到  对象的属性值的变化

    }
  },
  methods: {
    /**
     * 选中规则
     * 鼠标动作有以下几种
     * 1.鼠标左键按下
     *    选中当前的单元格
     * 2.鼠标左键按下并且拖动
     *        选中 起始点与与松开点的单元格
     * 3.鼠标右键按下
     *  弹出自定义菜单
     * -----------------------
     * 监听  mousedown mouseover  mouseup
     * ----------------
     */
    mouseDown(e) {
      let _this = this;
      _this.isMouseDown = !_this.isMouseDown;
      _this.selectCells = [];
      console.log("mouseDown", e);

    },
    endSelect(e) { // 结束框选
      if (!this.isEdit) {
        return
      }
      console.log("endSelect", e)
      this.mouseDownCell = null

    },
    mouseUp(e) {
      let _this = this;
      _this.isMouseDown = !this.isMouseDown;
      console.log("mounsUp", _this.selectCells);
    },
    mouseMove(event) {
      // console.log("mouseMove",event);
      let _this = this;
      if (!_this.isMouseDown || event.toElement.tagName.toLowerCase() == "table") { // 没有在表格中 按下鼠标
        return
      }
      // 获取当前 鼠标在表格中的位置
      let mouseEventDom = event.toElement.attributes;
      let selectedTd = mouseEventDom["dataSelectFlag"].value;
      if (_this.selectCells.indexOf(selectedTd) == -1) {
        _this.selectCells.push(selectedTd);
      }
      event.toElement.style = "background:#ffbb00";
    },
    //合并单元格
    mergingCell() {

    },
    getMenu(event) { // 获取菜单
      this.allowMerging = true
      // 拆分单元格 选中的是一个 或者 没有选中 且右击了单元格 同时 rouspan、colspan ！=1
      //  &&this.isSelectAllThemText()
      const sallowEdit = true
      this.menuList = [
        {label: '合并单元格', enable: true}, // 0
        {label: '拆分单元格', enable: true}, // 1
        {label: '设为结果列', enable: true}, // 2 tableModel
        {label: '插入行', enable: true}, // 3
        {label: '插入列', enable: true}, // 4
        {label: '删除行', hide: false, enable: true},
        {label: '删除列', hide: false, enable: true},
        {label: '设为可编辑单元', hide: true, enable: sallowEdit},
        {label: '设为不可编辑单元', hide: true, enable: sallowEdit},
        {label: '文本对齐方式', hide: true}, // 9
        {label: '清空内容', enable: true}
      ] // 6
      this.$nextTick(() => {
        // 是否加入合并单元格功能
        this.$refs[this.tableId + 'menu'].open(event, (index, val) => {
          switch (index) {
            case 0 :
              this.mergingCell();
              this.selectCells = [];
              break 		// 合并
            case 1 :
              this.cellSpilt();
              this.selectCells = [];
              break 		// 拆分 取消单元格选中
            case 2 :
              this.setResultCell();
              break 													// 设置结果列
            case 3 :
              this.inserRow(val);
              this.selectCells = [];
              break 			// 插入行
            case 4 :
              this.insertCol(val);
              this.selectCells = [];
              break 			// 插入列
            case 5 :
              this.removeRow();
              this.selectCells = [];
              break
            case 6 :
              this.removeCol();
              this.selectCells = [];
              break
            case 7 :
              this.setEditCell();
              break
            case 8 :
              this.setNoEditCell();
              break
            case 9 :
              this.setTextAligin(val);
              break
            case 10 :
              this.clearContent();
              break
          }
        })
      })
    }
  }
}
</script>

<style lang = "scss" scoped>
.select {
  background: #FAF0DE !important;
}

.isedit {
  background-color: #f2faf3 !important;
}

.dynamic-table-wapper {
  // padding:20px;
  // min-height: 200px;
  border-radius: 5px;
  overflow: hidden;
  // border:1px solid #dfe6ec;
  table-layout: fixed;

  .isPreview {
    user-select: auto !important;
  }

  .noPreview {
    user-select: none !important;
  }

  .dynamic-table {
    width: 100%;
    border-collapse: collapse;
    border: 1px solid #8F8F8F;

    &:first-child tr {
      th {
        border-top: none !important;
      }
    }

    tr {
      &:first-child th {
        border-top: none !important;
        border-left: none !important;
      }

      th:first-child, td:first-child {
        border-left: none !important;
      }

      th:last-child, td:last-child {
        border-right: none !important;
      }

      &:last-child td {
        border-bottom: none !important;
      }
    }

    th {
      // background-color: #F9FAFB;
      font-weight: 300;
    }

    td {
      font-size: 14px;
      color: #222222;
      // background-color: #ffffff;
    }

    td, th {
      word-wrap: break-word;
      border-spacing: 0;
      // border:1px solid #dfe6ec;
      box-sizing: border-box;
      padding: 5px;
      overflow-x: auto;
    }
  }
}

.brder-right-none {
  border-right: none !important;
}

.brder-bottom-none {
  border-bottom: none !important;
}

.table-title {
  text-align: center;
  padding: 10px 0;
  font-size: 16px;
  font-weight: 600;
}
</style>
